#include "common.h"

class TcpClient 
{
  public:
    TcpClient(const string& serverIp, const int serverPort)
      :_serverIp(serverIp)
      ,_serverPort(serverPort)
      ,_linkSock(-1)
    {}

    ~TcpClient()
    {
      if(_linkSock >= 0)
      {
        close(_linkSock);
      }
    }

    // 初始化客户端
    void InitClient()
    {
      // 初始化阶段只需创建套接字即可
      _linkSock = socket(AF_INET, SOCK_STREAM, 0);
    }

    // 连接成功后，发送信息给服务端，然后在接收服务端返回的信息
    void Request()
    {
      string msg;
      char echoBuff[1024];

      while(1)
      {
        cout<<"please enter# ";
        getline(cin, msg);
        write(_linkSock, msg.c_str(), msg.size());
        ssize_t size = read(_linkSock, echoBuff, sizeof(echoBuff)-1);
        if(size > 0)
        {
          echoBuff[size] = 0;
          cout<<"server echo# "<<echoBuff<<endl;;
        }
        else if(size == 0)
        {
          cout<<"server close!"<<endl;
          break;
        }
        else 
        {
          cerr<<"read error"<<endl;
          break;
        }
      }
    }


    // 启动客户端，用已经创建出来的套接字去连接服务端并请求其处理任务
    void Start()
    {
      struct sockaddr_in peer;
      memset(&peer, 0, sizeof(peer));
      peer.sin_family = AF_INET;
      peer.sin_port = htons(_serverPort);
      peer.sin_addr.s_addr = inet_addr(_serverIp.c_str());
      
      if(connect(_linkSock, (struct sockaddr*)&peer, sizeof(peer)) == -1)
      {
        cerr<<"connect error"<<endl;
      }
      else 
      {
        cout<<"connect success"<<endl;
        Request();
      }
    }

  private:
    string _serverIp;
    int _serverPort;
    int _linkSock;
};
